<?php

class WIPSBridge {
  var $wipslocation;
  var $pythonlocation;
  var $descriptorspec;
  
  function WIPSBridge($pythonlocation, $wipslocation) {
    $this->wipslocation = $wipslocation;
    $this->pythonlocation = $pythonlocation;
    
    $this->descriptorspec = array(
       0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
       1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
       //2 => array("file","c:\\error.txt","a")
    );
  }
  
  function getPosition($apInfos) {
    $process = proc_open(escapeshellarg($this->pythonlocation." wipsbridge.py"), $this->descriptorspec, $pipes, $this->wipslocation);
    if (is_resource($process) && is_array($apInfos) && count($apInfos) > 0) {
      
      //prendo i dati apInfos e li trasformo prima di passarli a Python
      foreach($apInfos as $ap) {
        $macs[] = $ap[0];
        $strenghts[] = $ap[1];
      }
      
      //Impacchetto il tutto
      $python_input = array("getPosition", array($macs, $strenghts));
      fwrite($pipes[0], serialize($python_input));
      fclose($pipes[0]);
    
      $python_output = stream_get_contents($pipes[1]);
      fclose($pipes[1]);
    
      $return_value = proc_close($process);
      
      $python_unserialized = unserialize($python_output);
      if(is_array($python_unserialized) && count($python_unserialized) > 0) {
        return $python_unserialized;
      } else {
        return array(-1, 0, 0, 0);
      }
    } else {
      return array(-1, 0, 0, 0);
    }
    
  }
  
  function getMapUrl($floor_id) {
    $process = proc_open(escapeshellarg($this->pythonlocation." wipsbridge.py"), $this->descriptorspec, $pipes, $this->wipslocation);
    if (is_resource($process) && !empty($floor_id)) {
      
      //Impacchetto il tutto
      $python_input = array("getMapUrl", $floor_id);

      fwrite($pipes[0], serialize($python_input));
      fclose($pipes[0]);
    
      $python_output = stream_get_contents($pipes[1]);
      fclose($pipes[1]);
    
      $return_value = proc_close($process);
      
      $python_unserialized = unserialize($python_output);
      
      if(!empty($python_unserialized)) {
        return $python_unserialized;
      } else {
        return "";
      }
      return $python_output;
    } else {
      return "";
    }
    
  }
  
}